import { createRouter, createWebHistory, onBeforeRouteLeave } from 'vue-router'

const routes = [
  {
    path: '/layout', component: () => import("@/views/Layout.vue"),
    children: [
      { path: 'home', components: { default: () => import("@/views/Home.vue"), sidebar: () => import("@/views/Sidebar.vue") } },
      { path: 'about', components: { default: () => import("@/views/About.vue"), sidebar: () => import("@/views/Sidebar.vue") } },
    ]
  },
  {
    path: '/parent/:id', name: 'parent', meta: { title: '父路由' }, component: () => import("@/views/Parent.vue"), children: [
      { path: 'child1/:name', name: 'child1', component: () => import("@/views/Child1.vue") },
      { path: 'child2/:name', name: 'child2', component: () => import("@/views/Child2.vue") },
      {
        path: 'child/:name', name: 'child', component: () => import("@/views/Child.vue"), children: [
          { path: 'grandchild/:code', name: 'grandchild', component: () => import("@/views/Grandchild.vue") }
        ]
      },
    ]
  },
  {
    path: '/home', meta: { title: '首页' }, component: () => import("@/views/Home.vue"), children: [
      { path: 'products',name:'products', component: () => import("@/views/Products.vue"),children:[
        {path:'products/:id',component:()=>import("@/views/Good.vue")}
      ] },
      { path: 'cart',name:'cart', component: () => import("@/views/Cart.vue") },
      { path: 'user',name:'user', component: () => import("@/views/User.vue") },
    ]
  },
  {
    path: '/about', meta: { title: '关于页' }, component: () => import("@/views/About.vue"), children: [
      { path: 'team', component: () => import("@/views/Team.vue") },
      { path: 'history', component: () => import("@/views/History.vue") },
    ],
  },
  { path: '/user/:id', meta: { title: '用户页' }, component: () => import("@/views/User.vue") },

]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior() {
    console.log('滚动到顶部');
    return { top: 0 }
  }
})

// 全局守卫
router.beforeEach((to, form, next) => {
  if (to.path === '/about') {
    if (confirm('确定要访问关于页面吗?')) {
      return next()
    }
  }
  document.title = to.meta.title
  next()
})

export default router
